package XianChengAnQuan;

public class TestSynchronized {
    public static void main(String[] args) {
        XianChengAnQuan.Account account = new XianChengAnQuan.Account("6002","123456",200);
       //俩个线程对象共享同一银行卡资源对象
        //临界资源对象只有一把锁
        Thread husband = new Thread(new XianChengAnQuan.HusBand(account),"丈夫");
        Thread wife = new Thread(new XianChengAnQuan.Wife(account),"妻子");
            husband.start();
            wife.start();
    }
}

class HusBand implements Runnable{
        XianChengAnQuan.Account acc;
        public HusBand(XianChengAnQuan.Account acc) {
            this.acc = acc;
        }
        //线程任务:取款
    public void run(){
            synchronized(acc){//对临界资源对象加锁
                this.acc.withdrawal("6002","123456",120);//原子操作
        }//还锁

    }
    }

class Wife implements Runnable{
    XianChengAnQuan.Account acc;
    public Wife(XianChengAnQuan.Account acc) {
        this.acc = acc;
    }
    //线程任务:取款
    public void run(){
        synchronized(acc){//对临界资源对象加锁
            this.acc.withdrawal("6002","123456",120);//原子操作
        }

    }
}

//银行账号,银行卡
class Account{
    String cardNo;
    String password;
    double balance;

    public Account() {
    }

    public Account(String cardNo, String password, double balance) {
        this.cardNo = cardNo;
        this.password = password;
        this.balance = balance;
    }
    //取款:原子操作,不可缺少或者打乱
    public void withdrawal(String no,String pwd,double money){
        System.out.println(Thread.currentThread().getName()+"正在读卡");
    if (no.equals(this.cardNo)&&pwd.equals(this.password)) {
        System.out.println(Thread.currentThread().getName()+"验证成功");
        if (money <= this.balance) {
            try {
                Thread.sleep(100);//ATm数钱
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            this.balance = this.balance - money;
            System.out.println(Thread.currentThread().getName()+"取钱成功! 当前余额为" + this.balance);
        } else {
            System.out.println(Thread.currentThread().getName()+"当前卡内余额不足");
        }
    }else {
        System.out.println("卡号或者密码错误");
        }
    }
    }

